<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\Labourer;
use App\Models\LabourerWage;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class LabourerService
{
    public function get($search,$project_id){
        $sql = Labourer::when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('name','like', '%'.$search.'%');
            });
        })->when($project_id, function ($query, $project_id) {
            return $query->where('project_id',$project_id);
        });
        return $sql;
    }


    public function insert($input,$project_id){
        $res = [];
        foreach ($input as $k => $v) {
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        $is = Labourer::where('mobile',$res['mobile'])->where('project_id',$project_id)->first();
        if($is){
            throw new InvalidRequestException('该手机号码已存在');
        }
        try {
            $res['password'] = Hash::make($res['password']);
            return Labourer::create($res);
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        try {
            $data = Labourer::find($input['id']);
            foreach ($input as $k => $v) {
                $data->$k = $v;
            }
            $data->save();
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function wage($search,$project_id){
        $sql = LabourerWage::when($project_id, function ($query, $project_id) {
            return $query->where('project_id',$project_id);
        })->with('labourer');
        return $sql;
    }


    public function insertWage($input,$project_id){
        $res = [];
        foreach ($input as $k => $v) {
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        try {
            return LabourerWage::create($res);
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function updateWage($input){
        try {
            $data = LabourerWage::find($input['id']);
            foreach ($input as $k => $v) {
                $data->$k = $v;
            }
            $data->save();
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

}